<template>
  <div class="system-edit-dic-container">
    <el-dialog :title="(ruleForm.id !== 0 ? '修改' : '添加') + '网络组件'" v-model="isShowDialog" width="769px"
               draggable>
      <el-form :model="ruleForm" ref="formRef" :rules="rules" size="default" label-width="90px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-cascader
              :options="deptTree"
              :props="{ checkStrictly: true, emitPath: false, value: 'deptId', label: 'deptName' }"
              placeholder="请选择所属部门"
              clearable
              v-model="ruleForm.deptId"
              style="width: 60%"
          >
            <template #default="{ node, data }">
              <span>{{ data.deptName }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择类型" clearable>
            <el-option v-for="item in typeData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description" style="margin-top: 20px">
          <el-input v-model="ruleForm.description" type="textarea" placeholder="请输入描述"/>
        </el-form-item>
        <div v-for="item in typeData" style="width: 90%; margin-left: 40px">
          <el-card tyle="width: 200px" shadow="always" :body-style="{ padding: '10px 30px 15px 0px' }"
                   v-if="item.id === ruleForm.type">
            <template #header> MQTT客户端配置卡片</template>
            <el-form-item label="客户端ID" prop="mqttClientConfig.clientId">
              <el-input v-model="ruleForm.mqttClientConfig.clientId" placeholder="请输入客户端ID"/>
            </el-form-item>
            <el-form-item label="远程地址" prop="mqttClientConfig.remoteHost">
              <el-input v-model="ruleForm.mqttClientConfig.remoteHost" placeholder="请输入远程地址"/>
            </el-form-item>
            <el-form-item label="远程端口" prop="mqttClientConfig.remotePort">
              <el-input-number v-model="ruleForm.mqttClientConfig.remotePort" placeholder="请输入远程端口"/>
            </el-form-item>
            <el-form-item label="安全" prop="mqttClientConfig.secure">
              <el-radio-group v-model="ruleForm.mqttClientConfig.secure">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="证书" prop="mqttClientConfig.certId" v-if="ruleForm.mqttClientConfig.secure">
              <el-select v-model="ruleForm.mqttClientConfig.certId" placeholder="请输入证书" clearable>
                <el-option v-for="item in certOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户名" prop="mqttClientConfig.username">
              <el-input v-model="ruleForm.mqttClientConfig.username" placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item label="密码" prop="mqttClientConfig.password">
              <el-input v-model="ruleForm.mqttClientConfig.password" placeholder="请输入密码"/>
            </el-form-item>
            <el-form-item label="消息长度" prop="mqttClientConfig.maxMessageSize">
              <el-input-number v-model="ruleForm.mqttClientConfig.maxMessageSize" placeholder="请输入消息长度"/>
            </el-form-item>
          </el-card>
        </div>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">
						{{ ruleForm.id !== 0 ? '修 改' : '添 加' }}
					</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {defineComponent, reactive, ref, toRefs, unref} from 'vue';
import {ElMessage} from 'element-plus';
import {addNetWork, editNetWork, getNetWork} from '/@/api/iot/network';

interface RuleFormState {
  id: number;
  deptId: number;
  name: string;
  configuration: string;
  state: number;
  type: string;
  description: string;
  // mqtt客户端配置
  mqttClientConfig: {
    clientId: string;
    remoteHost: string;
    remotePort: number;
    secure: boolean;
    certId: string;
    username: string;
    password: string;
    maxMessageSize: number;
  };
}

interface DicState {
  isShowDialog: boolean;
  ruleForm: RuleFormState;
  rules: {};
  certOptions: Array<object>;
}

export default defineComponent({
  name: 'networkEdit',
  props: {
    typeData: {
      type: Array,
      default: () => [],
    },
    deptTree: {
      type: Array,
      default: () => [],
    },
  },
  setup(prop, {emit}) {
    const formRef = ref<HTMLElement | null>(null);
    const validateDeptId = (rule: any, value: any, callback: any) => {
      if (value === 0) {
        callback(new Error('所属部门不能为空'));
      } else {
        callback();
      }
    };
    const state = reactive<DicState>({
      isShowDialog: false,
      ruleForm: {
        id: 0,
        deptId: 0,
        name: '',
        configuration: '',
        state: 0,
        type: '',
        description: '',
        // mqtt客户端配置
        mqttClientConfig: {
          clientId: '',
          remoteHost: '',
          remotePort: 1883,
          secure: false,
          certId: '',
          username: '',
          password: '',
          maxMessageSize: 8096,
        },
      },
      rules: {
        deptId: [
          {required: true, message: '所属部门不能为空', trigger: 'blur'},
          {validator: validateDeptId, trigger: 'blur'},
        ],
        name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
        type: [{required: true, message: '类型不能为空', trigger: 'blur'}],
        // mqtt客户端配置规则
        'mqttClientConfig.clientId': [{required: true, message: '客户端ID不能为空', trigger: 'blur'}],
        'mqttClientConfig.remoteHost': [{required: true, message: '远程地址不能为空', trigger: 'blur'}],
        'mqttClientConfig.username': [{required: true, message: '用户名不能为空', trigger: 'blur'}],
        'mqttClientConfig.password': [{required: true, message: '密码不能为空', trigger: 'blur'}],
      },
      // 证书列表
      certOptions: [],
    });
    // 打开弹窗
    const openDialog = (id: number | null) => {
      resetForm();
      if (id) {
        getNetWork(id).then((res: any) => {
          const data: RuleFormState = res.data.data;
          state.ruleForm.id = data.id;
          state.ruleForm.deptId = data.deptId;
          state.ruleForm.name = data.name;
          state.ruleForm.configuration = data.configuration;
          state.ruleForm.state = data.state;
          state.ruleForm.type = data.type;
          state.ruleForm.description = data.description;
          if (res.data.data.configuration != '') {
            let configuration = JSON.parse(res.data.data.configuration);
            // mqtt客户端配置
            if (data.type === 'MQTT_CLIENT') {
              state.ruleForm.mqttClientConfig.clientId = configuration.clientId.split("#")[0];
              state.ruleForm.mqttClientConfig.remoteHost = configuration.remoteHost;
              state.ruleForm.mqttClientConfig.remotePort = configuration.remotePort;
              state.ruleForm.mqttClientConfig.secure = configuration.secure;
              if (configuration.certId == 0) {
                state.ruleForm.mqttClientConfig.certId = '';
              } else {
                state.ruleForm.mqttClientConfig.certId = configuration.certId;
              }
              state.ruleForm.mqttClientConfig.username = configuration.username;
              state.ruleForm.mqttClientConfig.password = configuration.password;
              state.ruleForm.mqttClientConfig.maxMessageSize = configuration.maxMessageSize;
            }
          }
        });
      }
      state.isShowDialog = true;
    };
    // 重置表单
    const resetForm = () => {
      state.ruleForm = {
        id: 0,
        deptId: 0,
        name: '',
        configuration: '',
        state: 0,
        type: '',
        description: '',
        // mqtt客户端配置
        mqttClientConfig: {
          clientId: '',
          remoteHost: '',
          remotePort: 1883,
          secure: false,
          certId: '',
          username: '',
          password: '',
          maxMessageSize: 8096,
        },
      };
    };
    // 关闭弹窗
    const closeDialog = () => {
      state.isShowDialog = false;
      emit('dataList');
    };
    // 取消
    const onCancel = () => {
      closeDialog();
    };
    // 新增
    const onSubmit = () => {
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        if (valid) {
          saveOrUpSetParams();
          if (state.ruleForm.id !== 0) {
            //修改
            editNetWork(state.ruleForm).then(() => {
              ElMessage.success('修改成功');
              closeDialog(); // 关闭弹窗
            });
          } else {
            //添加
            addNetWork(state.ruleForm).then(() => {
              ElMessage.success('添加成功');
              closeDialog(); // 关闭弹窗
            });
          }
        }
      });
    };
    // 保存和更新时设置参数
    const saveOrUpSetParams = () => {
      let configuration;
      if (state.ruleForm.type == 'MQTT_CLIENT') {
        configuration = {
          clientId: '',
          remoteHost: '',
          remotePort: 0,
          secure: false,
          certId: 0,
          username: '',
          password: '',
          maxMessageSize: 0
        };
        if (state.ruleForm.mqttClientConfig.clientId) configuration.clientId =
            state.ruleForm.mqttClientConfig.clientId + "#" + Date.now();
        if (state.ruleForm.mqttClientConfig.remoteHost) configuration.remoteHost = state.ruleForm.mqttClientConfig.remoteHost;
        if (state.ruleForm.mqttClientConfig.remotePort) configuration.remotePort = state.ruleForm.mqttClientConfig.remotePort;
        if (state.ruleForm.mqttClientConfig.secure) configuration.secure = state.ruleForm.mqttClientConfig.secure;
        if (state.ruleForm.mqttClientConfig.certId) configuration.certId = parseInt(state.ruleForm.mqttClientConfig.certId);
        if (state.ruleForm.mqttClientConfig.username) configuration.username = state.ruleForm.mqttClientConfig.username;
        if (state.ruleForm.mqttClientConfig.password) configuration.password = state.ruleForm.mqttClientConfig.password;
        if (state.ruleForm.mqttClientConfig.maxMessageSize) configuration.maxMessageSize = state.ruleForm.mqttClientConfig.maxMessageSize;
      }
      state.ruleForm.configuration = JSON.stringify(configuration);
    };
    return {
      saveOrUpSetParams,
      openDialog,
      closeDialog,
      onCancel,
      onSubmit,
      formRef,
      ...toRefs(state),
    };
  },
});
</script>
